package com.shanwen.shopping.http;

import com.classic.okhttp.base.callback.StringCallback;
import org.json.JSONObject;

/**
 * 通用解析
 * <pre>使用fastjson进行解析</pre>
 */
public abstract class BaseCallback extends StringCallback {

    private static final int SUCCESS_CODE = 1000;
    private static final String KEY_CODE = "resultCode";
    private static final String KEY_OBJECT = "returnObject";
    private static final int DEFAULT_ERROR_CODE = -1;

    @Override public void onSuccess(String json) {
        if (null == json || "".equals(json) || json.length() == 0 || json.equals("null")) {
            onError(DEFAULT_ERROR_CODE, "");
            return;
        }
        try {
            final int code = new JSONObject(json).getInt(KEY_CODE);
            final String content = new JSONObject(json).getString(KEY_OBJECT);
            if (code == SUCCESS_CODE) {
                parse(filter(content));
            } else {
                onError(code, content);
            }
        } catch (Exception e) {
            onError(DEFAULT_ERROR_CODE, "");
            e.printStackTrace();
        }
    }

    public abstract void parse(String data);

    public String filter(String json) { return json; }
}
